package service

import (
	"fmt"
	"zhonghui/console/warehouse/cfgx"
	"zhonghui/console/warehouse/logx"

	"github.com/ddliu/go-httpclient"
	jsoniter "github.com/json-iterator/go"
)

type WelcomeCodeResponse struct {
	Errcode int64  `json:"errcode"`
	Errmsg  string `json:"errmsg"`
}

type WelcomeCodeReq struct {
	Attachments []Attachments `json:"attachments"`
	Text        Text          `json:"text"`
	WelcomeCode string        `json:"welcome_code"`
}

type Attachments struct {
	Link    Link   `json:"link"`
	Msgtype string `json:"msgtype"`
}
type Link struct {
	Desc   string `json:"desc"`
	Picurl string `json:"picurl"`
	Title  string `json:"title"`
	URL    string `json:"url"`
}

type Text struct {
	Content string `json:"content"`
}

func PushWelcomeCode(welcomeCode, content, accessToken string) (*WelcomeCodeResponse, error) {
	data := &WelcomeCodeResponse{}

	body := WelcomeCodeReq{
		WelcomeCode: welcomeCode,
		Text: Text{
			Content: content,
		},
	}

	jsonBody, err := jsoniter.MarshalToString(body)
	if err != nil {
		return nil, err
	}

	host := cfgx.Cfg().GetString("wx.host")
	url := fmt.Sprintf("%s/cgi-bin/externalcontact/send_welcome_msg?access_token=%s", host, accessToken)

	res, err := httpclient.PostJson(url, jsonBody)
	if err != nil {
		return nil, err
	}
	ret, err := res.ToString()
	if err != nil {
		return nil, err
	}

	logx.Zap().Infow("GetEmployeeActiveList", "ret", ret)

	return data, jsoniter.UnmarshalFromString(ret, data)
}
